package ar.com.photo_admin.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import ar.com.photo_admin.Constants;
import ar.com.photo_admin.R;
import ar.com.photo_admin.domain.Album;
import ar.com.photo_admin.domain.Photo;
import ar.com.photo_admin.exception.UnreachableNetworkException;
import ar.com.photo_admin.services.ServiceLayer;
import ar.com.photo_admin.services.Services;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;

public class PhotoGridActivity extends Activity {
	
	private Album album;
	
	private List<Photo> photos = new ArrayList<Photo>();

	private ArrayAdapter<Photo> adapter;
	
	private ServiceLayer service;
	
	private DisplayImageOptions options;

	private ImageLoader imageLoader = ImageLoader.getInstance();

	private boolean instanceStateSaved;

	private String token;
	
	private Long albumId;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.album_photo_grid);
		
		service = Services.createServiceLayer(this);
		
		if (savedInstanceState != null) {
			token = savedInstanceState.getString(Constants.TOKEN);
			albumId = savedInstanceState.getLong(Constants.ALBUM_ID);
			
		} else {
			Bundle extras = getIntent().getExtras();
			
			token = extras.getString(Constants.TOKEN);
			albumId = extras.getLong(Constants.ALBUM_ID);
		}
		
		options = new DisplayImageOptions.Builder()
			.showStubImage(R.drawable.ic_stub)
			.showImageForEmptyUri(R.drawable.ic_empty)
			.cacheInMemory()
			.cacheOnDisc()
			.bitmapConfig(Bitmap.Config.RGB_565)
			.build();
		
		adapter = (new ArrayAdapter<Photo>(this,
				R.layout.item_list_image, photos) {
			
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				
				final ImageView imageView;
				
				if (convertView == null) {
					imageView = (ImageView) getLayoutInflater().inflate(R.layout.item_album_photo_grid, parent, false);
				} else {
					imageView = (ImageView) convertView;
				}

				imageLoader.displayImage(photos.get(position).getThumbnailUrl(), imageView, options);

				return imageView;
			}
		});
		
		GridView gridView = (GridView) findViewById(R.id.gridview);
		
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				
				Intent intent = new Intent(PhotoGridActivity.this, PhotoPagerActivity.class);
				intent.putExtra(Constants.ALBUM, album);
				intent.putExtra(Constants.PHOTO_POSITION, position);
				
				startActivity(intent);				
			}
		});
		gridView.setOnScrollListener(new PauseOnScrollListener(true, true));
		
		new DownloadAlbumTask(token, albumId).execute();	
	}
	
	private class DownloadAlbumTask extends AsyncTask<Void, Void, Album> {

		private ProgressDialog dialog = null;
		
		private String token;
		
		private Long albumId;
		
		private Boolean connectionProblem = false;
		
		public DownloadAlbumTask(String token, Long albumId) {
			this.token = token;
			this.albumId = albumId;
		}
		
		@Override
		protected void onPreExecute() {
		
			dialog = new ProgressDialog(PhotoGridActivity.this);
			dialog.setTitle(getString(R.string.loading));
			dialog.setMessage(getString(R.string.loading_photos));
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			dialog.show();
		}
		
		@Override
		protected Album doInBackground(Void... params) {
			Album album = null;
			
			try {
				album = service.getAlbum(token, albumId);
			} catch (UnreachableNetworkException e) {
				connectionProblem = true;
			}
			
			return album;
		}
		
		@Override
		protected void onPostExecute(Album album) {
			
			photos.clear();
			
			if (connectionProblem) {
				Toast.makeText(PhotoGridActivity.this, R.string.connection_problem, Toast.LENGTH_SHORT).show();
				finish();
			} else {
				PhotoGridActivity.this.album = album;
				PhotoGridActivity.this.setTitle(album.getName());
				
				photos.addAll(album.getPhotos());
				adapter.notifyDataSetChanged();
			}			
		
			this.dialog.dismiss();
		}
	}	
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		
		instanceStateSaved = true;
		outState.putString(Constants.TOKEN, token);
		outState.putLong(Constants.ALBUM_ID, albumId);
	}

	@Override
	protected void onDestroy() {
		if (!instanceStateSaved) {
			imageLoader.stop();
		}
		super.onDestroy();
	}
}
